#ifndef __HF_LIST_H__
#define __HF_LIST_H__

#include "hf_core_common.h"

struct hf_list_head {
    struct hf_list_head *next;
    struct hf_list_head *prev;
};

// 初始化链表头
#define HF_LIST_HEAD_INIT(name) { &(name), &(name) }
#define HF_LIST_HEAD(name) struct hf_list_head name = HF_LIST_HEAD_INIT(name)

// 静态初始化链表节点
static inline void hf_init_list_head(struct hf_list_head *list)
{
    list->next = list;
    list->prev = list;
}

// 获取包含 hf_list_head 的父结构
#define hf_container_of(ptr, type, member) ({ \
    const typeof(((type *)0)->member) *__mptr = (ptr); \
    (type *)((char *)__mptr - offsetof(type, member)); \
})

// 遍历链表
#define hf_list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

// 遍历链表（安全版，允许删除）
#define hf_list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)

// 添加节点到链表头部
static inline void hf_list_add(struct hf_list_head *head, struct hf_list_head *new)
{
    new->next = head->next;
    new->prev = head;
    head->next->prev = new;
    head->next = new;
}

// 添加节点到链表尾部
static inline void hf_list_add_tail(struct hf_list_head *head, struct hf_list_head *new)
{
    new->prev = head->prev;
    new->next = head;
    head->prev->next = new;
    head->prev = new;
}

// 从链表中删除节点
static inline void hf_list_del(struct hf_list_head *entry)
{
    entry->prev->next = entry->next;
    entry->next->prev = entry->prev;
    entry->next = entry;
    entry->prev = entry;
}

// 判断链表是否为空
static inline int hf_list_empty(const struct hf_list_head *head)
{
    return head->next == head;
}

#endif /* __HF_LIST_H__ */